package com.example.flowable.service;

import jakarta.annotation.Resource;
import org.flowable.engine.*;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LeaveProcessService {

    @Resource
    private RepositoryService repositoryService;

    @Resource
    private RuntimeService runtimeService;

    @Resource
    private TaskService taskService;

    @Resource
    private HistoryService historyService;

    @Resource
    IdentityService identityService;


    // 启动请假流程
    @Transactional
    public String startProcess(String initiator, int days) {
        Map<String, Object> variables = new HashMap<>();
        variables.put("initiator", initiator);
        variables.put("days", days);
        ProcessInstance instance = runtimeService.startProcessInstanceByKey(
                "leaveProcess", variables
        );
        return instance.getId();
    }


    /**
     * 初始化流程
     *
     * @method: initFlow
     * @return:
     * @author: xie
     * @date: 2024/12/24 上午9:26
     **/
    @GetMapping("initFlow")
    @Transactional(rollbackFor = Exception.class)
    public void initFlow() throws IOException {
        // 获取bpmn文件夹的所有.bpmn20.xml文件
        ClassPathResource bpmnFolder = new ClassPathResource("bpmn/");
        var files = bpmnFolder.getFile().listFiles((dir, name) -> name.endsWith(".bpmn20.xml"));

        if (files != null && files.length > 0) {
            // 创建部署对象
            var deploymentBuilder = repositoryService.createDeployment();

            for (var file : files) {
                // 添加BPMN文件到部署
                deploymentBuilder.addInputStream(file.getName(), file.toURI().toURL().openStream());
            }

            // 执行部署
            Deployment deployment = deploymentBuilder.deploy();
        }
    }


    // 查询用户任务
    @Transactional
    public List<Task> getUserTasks(String userId) {
        return taskService.createTaskQuery()
                .taskAssignee(userId)
                .list();
    }

    // 完成任务（带审批结果）
    @Transactional
    public void completeTask(String taskId, boolean approved) {
        Map<String, Object> vars = new HashMap<>();
        vars.put("approved", approved);
        taskService.complete(taskId, vars);
    }
}